{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.utils.data as Data  \n",
    "from _02PipeDatasetLoader import PipeDataset\n",
    "from torchvision.transforms import transforms\n",
    "\n",
    "trans=transforms.ToTensor()\n",
    "datapath=\"..\\\\Dataset\\\\Train\"\n",
    "pipe=PipeDataset(datapath,trans,trans)\n",
    "trainiter=Data.DataLoader(pipe,4,shuffle=True,num_workers=0,drop_last=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from _03Deeplabv3plus import DeepLabV3\n",
    "torch.cuda.set_device(0)\n",
    "net=DeepLabV3(class_num=2)\n",
    "net=net.to(\"cuda\")\n",
    "Criterion = nn.BCELoss().to('cuda')\n",
    "Optimizer = torch.optim.Adam(net.parameters(), lr=0.01)\n",
    "epochs=200\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "训练过程\n",
    "'''\n",
    "\n",
    "import gc\n",
    "for epoch in range(epochs):\n",
    "    net.train()     \n",
    "    gc.collect()\n",
    "    torch.cuda.empty_cache()\n",
    "    loss=0\n",
    "    for data in trainiter:\n",
    "        \n",
    "        img,label=data\n",
    "        imgg=img.to(\"cuda\")\n",
    "        labelg=label.to(\"cuda\")\n",
    "        Optimizer.zero_grad()\n",
    "        with torch.set_grad_enabled(True):\n",
    "            OutputImg = net(imgg)\n",
    "            #print(OutputImg.size())\n",
    "            #print(label.size())\n",
    "            BatchLoss = Criterion(OutputImg, labelg)\n",
    "            BatchLoss.backward(retain_graph=False)\n",
    "            Optimizer.step()\n",
    "            loss+=BatchLoss.item()\n",
    "    print(loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "net=net.to(\"cuda\")\n",
    "torch.save(net.state_dict(),\"..\\\\Model\\\\model_01.pth\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "space_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.15"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
